<script lang="ts">
import type { SelectProps } from 'ant-design-vue';
import CurrencyList from '~/components/currency/CurrencyList.vue';

interface TProps {
  list?: { currency: string; balance?: string }[];
  showBalance?: boolean;
  showHideZeroBalanceBtn?: boolean;
  showConvertToFiatBtn?: boolean;
  allowClear?: boolean;
  placeholder?: string;
  bordered?: boolean;
  size?: SelectProps['size'];
  labelAlign?: 'left' | 'center';
  disabled?: boolean;
}
</script>

<script setup lang="ts">
const props = withDefaults(defineProps<TProps>(), {
  labelAlign: 'center',
  bordered: undefined,
});
const currency = defineModel<string | undefined>('value');

const $currencySelect = ref<any>();
const currencyStore = useCurrencyStore();
const currencyList = computed(() => props.list || currencyStore.currencyList || []);
const currencyOptions = computed(() => {
  const options = currencyList.value?.map(item => ({
    value: item.currency,
    label: item.currency,
  }));
  return options;
});

// 为了在选择币种后关闭选择框
function blurCurrencySelect() {
  $currencySelect.value?.blur?.();
  const parentEle: HTMLElement = $currencySelect.value?.$el.parentElement;
  const clickEv = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
  parentEle?.dispatchEvent(clickEv);
}
</script>

<template>
  <ASelect
    ref="$currencySelect"
    v-model:value="currency" class="select-currency"
    :class="[$attrs.class, props.labelAlign === 'center' && 'center-align', props.labelAlign === 'left' && 'left-align']"
    :options="currencyOptions" :allowClear="props.allowClear" :bordered="props.bordered"
    :dropdownMatchSelectWidth="false" :placeholder="props.placeholder || 'Select Currency'"
    :size="props.size" :disabled="props.disabled"
    :getPopupContainer="(el: HTMLElement) => el.parentElement!"
  >
    <template #optionLabel="option">
      <div v-if="option" class="current-currency-option flex items-center">
        <TCurrencyIcon v-if="option.value" class="mr-1" :symbol="option.value" />
        <span>{{ option.label }}</span>
      </div>
    </template>
    <template #dropdownRender>
      <CurrencyList
        :value="currency"
        class="pointer-events-auto min-w-50 p-1.5" listClass="max-h-50"
        :currencyList="currencyList" :showConvertToFiatBtn="props.showConvertToFiatBtn"
        :showBalance="props.showBalance" :showHideZeroBalanceBtn="props.showHideZeroBalanceBtn"
        @update:value="[blurCurrencySelect(), currency = $event ?? '']"
      />
    </template>
  </ASelect>
</template>

<style lang="scss">
.select-currency.center-align {
  .current-currency-option {
    justify-content: center;
  }

  .ant-select-selector .ant-select-selection-placeholder {
    text-align: center;
  }
}
</style>
